const Router = require('koa-router');

const Admin = require('../models/admin')
const jwt = require('jsonwebtoken')


const getTimeStamp = {
  // 到期时间
  expireTime: () => {
    return Math.round(new Date()) + 60 * 1000 * 60 * 2
  },
  // 更新时间
  updateTime: () => {
    return Math.round(new Date())
  }
}

let router = new Router({
  prefix: '/api'
})

// admin登录
router.post('/login', async(ctx) => {
  const {
    account,
    password
  } = ctx.request.body

  const result = await Admin.find({
    account,
    password
  })
  if (result.length) {

    // jwt生成token
    const token = jwt.sign({
      name: account,
      _id: result[0]._id
    }, '前端摆渡人', { expiresIn: '2h' });
    await Admin.updateOne({_id: result[0]._id}, {token: token, expireTime: getTimeStamp.expireTime(), updateTime: getTimeStamp.updateTime()})
    ctx.body = {
      code: 0,
      token,
      msg: '登陆成功'
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '账号或密码错误'
    }
  }
})

router.post('/register', async(ctx) => {
  const {
    account,
    password
  } = ctx.request.body
  const user = await Admin.find({
    account
  })
  if (user.length) {
    ctx.body = {
      code: -1,
      msg: '账号已存在'
    }
    return
  }
  const result = await Admin.create({
    account,
    password
  })
  if (result) {
    ctx.body = {
      code: 0,
      msg: '注册成功'
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '注册失败'
    }
  }
})

module.exports = router